<template>
  <el-table
    ref="table"
    :key="key"
    :data="data"
    :height="height"
    stripe
    size="mini"
    header-row-class-name="c-table-header"
    header-cell-class-name="c-table-header"
    :row-key="primaryKey"
    :default-expand-all="defaultExpandAll"
    @selection-change="selectChange"
    @row-click="rowClick"
    class="c-table"
  >
    <el-table-column
      v-if="index"
      type="index"
      :index="1"
      align="center"
      :label="multLang('title_dl')"
    ></el-table-column>
    <el-table-column
      v-if="select"
      type="selection"
      fixed="left"
      align="center"
    ></el-table-column>
    <el-table-column
      v-for="col in cols"
      :key="col.prop"
      :label="col.label"
      :prop="col.prop"
      :width="col.width"
      :fixed="col.fixed"
      :show-overflow-tooltip="typeof col.tooltip === 'undefined' || col.tooltip"
      :align="col.align || 'center'"
    >
      <template slot="header" slot-scope="{ column }">
        {{ multLang(column.label) }}
      </template>
      <template slot-scope="{ row, column, $index }">
        <template v-if="col.route && col.route.auth">
          <el-button
            type="text"
            @click="
              toRoute(col.route.name, {
                id: row[col.route.key || primaryKey],
                ...col.route.params
              })
            "
          >
            {{
              col.formatter ? col.formatter(row, column, $index) : row[col.prop]
            }}
          </el-button>
        </template>
        <template v-else-if="col.switch">
          <c-switch
            :disabled="!col.switch.auth"
            :value="
              col.formatter
                ? col.formatter(row, column, $index)
                : String(row[col.prop])
            "
            :options="col.switch.list"
            @change="switchChange($event, row)"
          ></c-switch>
        </template>
        <template v-else-if="col.mod">
          <template v-if="col.mod.type === 'select' && col.mod.options">
            <c-select
              :disabled="!col.mod.auth"
              :value="
                col.formatter
                  ? col.formatter(row, column, $index)
                  : row[col.prop]
              "
              :options="col.mod.options"
              @change="
                modChange({
                  type: col.mod.type,
                  result: $event,
                  row,
                  col: column,
                  index: $index
                })
              "
              popper-append-to-body
            ></c-select>
          </template>
          <template v-else-if="col.mod.type === 'switch' && col.mod.options">
            <c-switch
              :disabled="!col.mod.auth"
              :value="
                col.formatter
                  ? col.formatter(row, column, $index)
                  : String(row[col.prop])
              "
              :options="col.mod.options"
              :color="col.mod.color"
              @change="
                modChange({
                  type: col.mod.type,
                  result: $event,
                  row,
                  col: column,
                  index: $index
                })
              "
            ></c-switch>
          </template>
          <template v-else>
            {{
              col.formatter ? col.formatter(row, column, $index) : row[col.prop]
            }}
          </template>
        </template>
        <template v-else>
          {{
            col.formatter ? col.formatter(row, column, $index) : row[col.prop]
          }}
        </template>
      </template>
    </el-table-column>
    <slot></slot>
    <!-- :fixed="opn.fixed || 'right'" -->
    <el-table-column
      v-if="$scopedSlots.opn"
      :width="opn.width || '200px'"
      :fixed="opn.fixed"
      :align="opn.align || 'center'"
    >
      <template #header>
        {{ multLang('title_action_a') }}
      </template>
      <template #default="{ row, column, $index }">
        <slot name="opn" :row="row" :column="column" :$index="$index"></slot>
      </template>
    </el-table-column>
    <template v-if="vols.length">
      <!-- fixed="right" -->
      <el-table-column width="50px" align="right">
        <template slot="header" slot-scope="{}">
          <el-popover popper-class="c-table-popper">
            <template slot="reference">
              <c-icon name="unorderedlist" class="c-table-popper-icon"></c-icon>
            </template>
            <div>
              <template v-for="vol in vols">
                <el-checkbox
                  v-model="vol.val"
                  :label="multLang(vol.key)"
                  :key="vol.key"
                ></el-checkbox>
              </template>
              <div class="c-table-popper-btn">
                <el-button size="mini" @click="reset">
                  <!-- 重置 -->
                  {{ multLang('btn_rst_a') }}
                </el-button>
                <el-button type="primary" size="mini" @click="yes">
                  <!-- 确定 -->
                  {{ multLang('btn_sure_a') }}
                </el-button>
              </div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
    </template>
  </el-table>
</template>
<script>
import { toRoute } from '@/util/router'
import { ObjectCopy } from '@/util'
export default {
  name: 'CTable',
  components: {},
  props: {
    primaryKey: { type: String, default: 'id' },
    data: {
      type: Array,
      default() {
        return []
      }
    },
    height: { type: String, default: '100%' },
    index: { type: Boolean, default: false },
    select: { type: Boolean, default: false },
    col: {
      type: Array,
      default() {
        return []
      }
    },
    opn: {
      type: Object,
      default() {
        return {}
      }
    },
    vol: {
      type: Array,
      default() {
        return []
      }
    },
    defaultExpandAll: { type: Boolean, default: false }
  },
  data() {
    return {
      layout: 0,
      keyout: 0,
      key: 1,
      cols: [],
      vols: []
    }
  },
  computed: {},
  watch: {
    data: {
      deep: true,
      handler() {
        this.refreshTable()
      }
    },
    col: {
      deep: true,
      immediate: true,
      handler() {
        this.setCols()
      }
    },
    vol: {
      deep: true,
      immediate: true,
      handler() {
        this.setVols()
        this.setCols()
      }
    }
  },
  beforeCreate() {},
  created() {},
  beforeMount() {},
  mounted() {},
  beforeUpdate() {},
  updated() {},
  activated() {
    this.refreshTable()
  },
  deactivated() {},
  beforeDestroy() {},
  destroyed() {},
  methods: {
    toRoute(name, params) {
      toRoute(name, { params, from: this.$route.name })
    },
    setCols() {
      this.cols = this.col.reduce((arr, item) => {
        if (item.hide) return arr
        const col = ObjectCopy(item)
        const { label } = col
        this.vol.length
          ? this.vols.forEach(
              ({ key, val }) => key === label && val && arr.push(col)
            )
          : arr.push(col)
        return arr
      }, [])
      this.refreshTable()
    },
    setVols() {
      this.vols = this.vol.reduce((arr, { key, val }) => {
        arr.push({ key, val })
        return arr
      }, [])
    },
    refreshLayout() {
      // console.log(
      //   '开始 refreshLayout',
      //   this.$refs.table ? '有table' : '无table'
      // )
      // if (!this.$refs.table) return
      // clearTimeout(this.layout)
      // this.layout = 0
      // this.layout = setTimeout(() => {
      //   this.$nextTick().then(() => {
      //     console.log('开始 doLayout')
      //     this.$refs.table && this.$refs.table.doLayout()
      //   })
      // })
    },
    refreshTable() {
      clearTimeout(this.keyout)
      this.keyout = 0
      this.keyout = setTimeout(() => {
        this.key++
      })
    },
    reset() {
      this.setVols()
    },
    yes() {
      this.setCols()
    },
    switchChange(...args) {
      this.$emit('switch-change', ...args)
    },
    selectChange(sels) {
      const ids = []
      const key = this.primaryKey
      const selen = sels.length
      sels.forEach(sel => {
        sel[key] && ids.push(sel[key])
      })
      this.$emit('select-change', ids.join(','), selen)
    },
    modChange(vals) {
      this.$emit('mod-change', vals)
    },
    rowClick(...args) {
      this.$emit('row-click', ...args)
    },
    rowSelect(row) {
      row && this.$refs.table.toggleRowSelection(row)
    }
  }
}
</script>
<style lang="scss">
.c-table-popper {
  box-sizing: border-box;
  &-icon {
    font-size: 18px;
    vertical-align: middle;
    cursor: pointer;
  }
  &-btn {
    text-align: center;
  }
  .el-checkbox {
    display: block;
    margin: 0 0 10px 0;
  }
}
@include admin {
  .c-table {
    &-header {
      background-color: #ecf6ff;
      color: #333;
    }
  }
}
</style>
